<template>
  <view class="page" :style="{'overflow':show?'hidden':''}">
    <scroll-view scroll-y="true" class="scroll-Y" :key="1" v-if="!show">
      <view class="context">
        <view class="title">
          <text>不知道写什么？试试这个</text>
          <image style="width: 48rpx;height: 24rpx;margin: 0 4px;" src="/static/create/create_finger.png"></image>
          <text style="color: #3F96F7" @click="select('人工智能')">企业发展</text>
        </view>
        <!--        -->
        <view class="context-tip">
          <view class="context-tip-left">
            <text>分析对象</text>
            <text class="context-tip-left-tip">*</text>
          </view>
          <!--            <view class="context-tip-right">至少包含10个字</view>-->
        </view>
        <view class="context-textarea">
          <textarea :value="message" placeholder="请输入分析对象" placeholder-style="color:#999999;font-size:24rpx"
            :maxlength="100" @input="changeMessage" class="context-textarea-input"></textarea>
          <view class="context-textarea-max">{{message.length}}/100</view>
        </view>
        <!--        -->
        <view class="context-tip">
          <view class="context-tip-left">
            <text>目标描述</text>
            <text class="context-tip-left-tip">*</text>
          </view>
          <!--            <view class="context-tip-right">至少包含50个字</view>-->
        </view>
        <view class="context-textarea" style="height: 150rpx">
          <textarea :value="writing" placeholder="请输入目标描述" placeholder-style="color:#999999;font-size:24rpx"
            :maxlength="100" @input="changeValue" class="context-textarea-input"></textarea>
          <view class="context-textarea-max">{{writing.length}}/100</view>
        </view>
        <!--        -->
        <view class="context-tip">
          <view class="context-tip-left">
            <text>优势/劣势关键词</text>
            <!--              <text class="context-tip-left-tip">*</text>-->
          </view>
          <view class="context-tip-right"></view>
        </view>
        <view class="context-textarea" style="height: 120rpx">
          <textarea :value="title" placeholder="请输入优势/劣势的关键词" placeholder-style="color:#999999;font-size:24rpx"
            :maxlength="100" @input="changeTitle" class="context-textarea-input"></textarea>
          <view class="context-textarea-max">{{title.length}}/100</view>
        </view>
        <!--        -->
        <view class="context-tip">
          <view class="context-tip-left">
            <text>外部机会/威胁关键词</text>
            <text class="context-tip-left-tip">*</text>
          </view>
          <view class="context-tip-right"></view>
        </view>
        <view class="context-textarea">
          <textarea :value="chance" placeholder="请输入外部机会/威胁关键词（<= 200）"
            placeholder-style="color:#999999;font-size:24rpx" :maxlength="100" @input="changeChance"
            class="context-textarea-input"></textarea>
          <view class="context-textarea-max">{{chance.length}}/100</view>
        </view>
        <!--        -->
        <!--        -->
        <view class="context-tip">
          <view class="context-tip-left">
            <text>结果字数</text>
            <text class="context-tip-left-tip">*</text>
          </view>
          <view class="context-tip-right"></view>
        </view>
        <view class="context-textarea" style="height: 80rpx">
          <textarea :value="outline" placeholder="请输入结果字数（<= 1000）" placeholder-style="color:#999999;font-size:24rpx"
            @input="changeOutline" class="context-textarea-input" style="margin-top: -9rpx"></textarea>
          <!-- <view class="context-textarea-max">{{outline.length}}/100</view> -->
        </view>
        <!--        -->
        <!-- <view class="context-title">
            <text>选择作文题材</text>
            <text class="context-title-tip"></text>
          </view>
          <view class="context-tone">
            <view class="context-tone-item" v-for="(item,index) in themeList" :key="index" @click="changeTheme(item,index)"
                  :class="{'context-tone-item-select':index==themeIndex}">{{item.text}}</view>
          </view> -->
        <!--        -->
        <!--        -->
        <!-- <view class="context-title">
            <text>选择语言</text>
            <text class="context-title-tip"></text>
          </view>
          <view class="context-tone">
            <view class="context-tone-item" v-for="(item,index) in languageList" :key="index" @click="changeLanguage(item,index)"
                  :class="{'context-tone-item-select':index==languageIndex}">{{item.text}}</view>
          </view> -->
        <!--        -->
        <!-- <view class="context-title">
            <text>选择语气</text>
            <text class="context-title-tip"></text>
          </view>
          <view class="context-tone">
            <view class="context-tone-item" v-for="(item,index) in toneList" :key="index" @click="changeTone(item,index)"
                  :class="{'context-tone-item-select':index==toneIndex}">{{item.text}}</view>
          </view> -->
        <!--        -->
        <view class="button" @click="create"
          :style="{'background-color':(writing.length>0&&message.length>0)?'rgb(52, 116, 255)':'rgba(52, 116, 255,.3)'}">
          开始生成</view>
        <view style="height: 80rpx"></view>
      </view>
    </scroll-view>
    <view class="page-view" v-if="show" :key="2">
      <view class="answer">
        <view class="answer-value">{{title?title:writing}}</view>
        <view class="answer-textarea">
          <textarea :value="creativeResult" :maxlength="-1" class="answer-textarea-input"></textarea>
          <view class="answer-fontLength">共{{creativeResult.length}}字</view>
        </view>
      </view>
      <view class="tabbar">
        <view class="tabbar-item" @click="clickTab(item,index)" v-for="(item, index) in tabbarList" :key="index">
          <view>
            <image style="width: 38rpx;height: 38rpx;margin-top:8rpx" :src="item.src"></image>
          </view>
          <view style="margin-left:30rpx">{{item.text}}</view>
        </view>
      </view>
    </view>
    <!--  进度条  -->
    <view class="schedule-page" v-if="scheduleShow">
      <view class="schedule-box">
        <view class="schedule-text">{{text}}</view>
        <view class="lineBox">
          <view class="lineAnimation" v-for="(item,index) in arrIndex" :key="index" :style="{'width':item.width+'%'}">
            <view v-if="item.widthChildren>0" class="lineAnimation-children" :style="{'width':item.widthChildren+'%'}">
            </view>
          </view>
        </view>
        <view class="schedule-number">{{schedule}}%</view>
      </view>
    </view>
  </view>
</template>
<script>
import {
  wycUrl,
  sslbiz,
  wycUrlApi
} from '@/api/assemb.js'
export default {
  data () {
    return {
      toneIndex: 0,
      toneList: [
        {
          text: '有说服力'
        },
        {
          text: '正式得体'
        },
        {
          text: '专业'
        },
        {
          text: '幽默'
        },
        {
          text: '热情'
        }
      ],
      languageIndex: 0,
      languageList: [
        {
          text: '中文'
        },
        {
          text: '英文'
        }
      ],
      themeIndex: 0,
      themeList: [
        {
          text: '记叙文'
        },
        {
          text: '抒情文'
        },
        {
          text: '议论文'
        },
        {
          text: '说明文'
        },
        {
          text: '应用文'
        },
        {
          text: '自定义'
        }
      ],
      show: false,
      message: '',
      languageItem: '中文',
      toneItem: '有说服力',
      themeItem: '议论文',
      writing: '',
      title: '',
      outline: '',
      chance: '',
      answer: '猫咪眯着眼睛，舒服的坐在沙发上。格子图案的地板，全息\n' +
        '图，VR，3D感。猫咪眯着眼睛，舒服的坐在沙发上。格子\n' +
        '图案的地板，全息图，VR，3D感。',
      tabbarList: [

        {
          src: '/static/create/create_continue1.png',
          text: '重新生成'
        },
        {
          src: '/static/create/create_copy1.png',
          text: '复制文本'
        }
      ],
      creativeResult: '',
      creativeResults: '',
      compareResults: '',
      originality: '',
      aiLevel: 0,
      width: 0,
      arrIndex: [],
      widthIndex: 0,
      schedule: 0,
      text: '创作中,请稍后',
      scheduleShow: false,
	  isVip:false
    }
  },
  onShow () {
     this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
  },
  onLoad (option) {

    this.frequency = uni.getStorageSync('frequency') || 3
    if (this.frequency != 1 && this.frequency != 2) {
      uni.setStorageSync('frequency', 3)
    } else {
    }
    console.log("?? ~ file: customInput.vue:138 ~ onLoad ~ this.frequency:", this.frequency)
    // callAPP()
  },
  methods: {
    func () {
      uni.setStorageSync('frequency', 3)
    },
    //进度条
    change () {
      clearTimeout(this.time);
      clearTimeout(this.time1);
      clearTimeout(this.times);
      var settext = [
        "创作中,请稍后",
        "优化中,请稍后",
        "下载中,请稍后",
        "合并中,请稍后",
        "上传中,请稍后"
      ];
      let inx = 0;
      this.widthIndex = 0;
      this.schedule = 0;
      this.arrIndex = this.arrIndex.map(item => {
        return {
          ...item,
          width: 100 / (this.arrIndex.length),
          widthChildren: 0
        };
      });

      // 计算总进度
      let sum = () => {
        let number = this.arrIndex
          .map((item) => item.widthChildren)
          .reduce((accumulator, currentValue) => accumulator + currentValue);
        this.schedule = Math.floor(number / this.arrIndex.length);
      };
      const loadNextProgress = () => {
        if (this.widthIndex >= this.arrIndex.length) {
          this.time = setTimeout(() => {
            this.widthIndex = 0; // 重置为0，从新循环
            console.log('下一个进度条')
            loadNextProgress();
          }, 100); // 等待 1s 后重新开始加载
          if (this.widthIndex >= this.arrIndex.length - 1) {
            this.arrIndex.forEach((item) => {
              item.widthChildren = 0;
            });
            inx += 1;
            if (inx > 4) {
              this.text = settext[4]
            } else {
              this.text = settext[inx]
            }
            this.schedule = 0;
            clearTimeout(this.time)
            this.time = null
          }
          this.time1 = setTimeout(() => {
            this.widthIndex = 0;
            loadNextProgress();
            clearTimeout(this.time1)
          }, 300);
          return;
        }
        if (this.widthIndex > 0) {
          // 如果是加载了第二个进度，则让上一个进度条伪 100%
          this.arrIndex[this.widthIndex - 1].widthChildren = 100;
        }
        if (this.arrIndex[this.widthIndex].widthChildren < 99) {
          this.arrIndex[this.widthIndex].widthChildren++;
          this.times = setTimeout(loadNextProgress, 300); // 间隔 100ms 执行下一次加载
        } else {
          this.widthIndex++; // 接着下一个进度跑
          loadNextProgress();
        }
        sum(); // 计算整体的进度值
      };
      loadNextProgress();
    },
    async original (param, i) {
      // uni.showLoading({
      //   title: '加载中...',
      //   mask: true
      // });
      console.log('2222')
      //   await wycUrl(param, 1009, 'magicChat').then((res) => {
      await wycUrl(param, 1005, 'chatAzure2').then((res) => {
        setTimeout(() => {
          this.scheduleShow = false
        }, 1000)
        if (res.data.code == 200) {
          this.writing = ''
          console.log('这是200的结果')
          let prams = {
            text: res.data.data.results[0]
          };
          sslbiz(prams, "1089", "DYTextCheck").then(async res => {
            console.log(res.hit, '这是返回结果的敏感词')
            if (res.hit) {
              res.data.data.results[0] = ''
              uni.showModal({
                title: '提示',
                content: "创作内容包含敏感词,系统已屏蔽！",
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定');
                  } else if (res.cancel) {
                    console.log('用户点击取消');
                  }
                }
              });
            }
          })
        } else if (res.data.code == 400) {
          this.writing = ''
          uni.showModal({
            title: '提示',
            content: res.data.message
          })
        } else {
          this.writing = ''
        }
        this.widthIndex++
       if (!this.isVip) {
						let param = {
							consumecoins: 1,
							descinfo: '一键创作消耗',
							consumetype: 1,
						}
						apiMixUrlApi(param, '1043', "ConsumeCoins").then(result => {
							console.log(result, '1043返回值');
							uni.setStorageSync('frequencyrs', result.coins)
						});
					}
        console.log('res=====>', res)
        this.creativeResult += res.data.data.results[0]
        this.show = true
        uni.hideLoading();
      }).catch(err => {
        setTimeout(() => {
          this.scheduleShow = false
        }, 1000)
        console.log('失败了~~', i, this.arrIndex[i], err)
        // this.scheduleShow = false
        let str = err
        if (str.slice(0, 12) == '') {
          str = str.slice(12)
        }
        console.log('str', str)
        let context = ''
        if (str.length > 20) {
          context = `${str.slice(0, 8)}......${str.slice(-8)}`
        } else {
          context = str
        }

        uni.showModal({
          title: '提示',
          content: `"${context}",以上内容含有违规，请整改`,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      })
    },
    // AI伪原创
    async highOriginal () {

      this.creativeResult = ''
      if (this.writing.trim() == '') {
        uni.showToast({
          title: '请输入内容',
          duration: 2000,
          icon: 'none'
        });
      } else if (uni.getStorageSync('frequency') > 1 || this.isVip) {
        let prams = {
          text: this.writing,
        };
        sslbiz(prams, "1089", "DYTextCheck").then(async res => {
          if (res.hit) {
            this.writing = ''
            uni.showModal({
              title: '提示',
              content: "检测到敏感关键词或文本为空，请修改后重试！",
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          } else {
            if (this.writing.trim().length < 400 || this.isVip) {
              let str = this.writing,
                arr = [] //用于保存每次截取后的字符串
              biali(str, 0);
              console.log(arr);

              function biali (x, z) {
                var m = x.substr(z, 200);
                var f = ['。', ',', '.', '?', ';', '!', '，', '？', '！', '；'];
                var y = 200;
                var ynum = [];
                for (var j = 0; j < f.length; j++) {
                  if (m.lastIndexOf(f[j]) > 0) {
                    ynum.push(m.lastIndexOf(f[j]));
                  }
                }
                if (ynum.length > 0) {
                  y = (Math.max.apply(null, ynum) + 1);
                }
                arr.push(x.substr(z, y));
                z += y;
                if (m.length >= 200) {
                  return biali(x, z);
                }
              }


              this.arrIndex = arr
              this.scheduleShow = true
              this.text = '创作中,请稍后'
              this.change()
              for (var i = 0; i < arr.length; i++) {


              }
              let param = {
                // "chatId": "123",
                // "content": `请使用平台为${this.toneItem}商品名称为${this.message }产品特点为${this.writing}生成与真实的商品优质好评`
                "content": `请使用目标描述为${this.writing}优势/劣势关键词为${this.title}最少${this.outline}字分析对象为${this.message}外部机会/威胁关键词${this.chance}进行创作`

              }
              await this.original(param, i)
              setTimeout(() => {
                this.scheduleShow = false
              }, 1000)

              uni.hideLoading();
            } else {
              uni.showToast({
                title: '字数超限了,开通会员不限字数。',
                duration: 2000,
                icon: 'none'
              });
              this.content = '字数超限了,开通会员不限字数。'
              this.vipShow = true
            }

          }
        })

      } else {
        this.isShowLoading = false;

        uni.showToast({
          title: '今日免费次数已用完,需开通会员才可使用',
          duration: 2000,
          icon: 'none'
        });
        // this.content = '今日免费次数已用完,需开通会员才可使用。'
        this.vipShow = true
      }
    },
    changeLanguage (item, index) {
      this.languageIndex = index
      this.languageItem = item.text
    },
    changeTone (item, index) {
      this.toneIndex = index
      this.toneItem = item.text
    },
    changeTheme (item, index) {
      console.log("?? ~ file: fullText.vue:481 ~ changeTheme ~ item:", item, index)
      this.themeIndex = index
      this.themeItem = item.text
    },
    select (e) {
      this.message = '企业'
      this.writing = '寻求更好发展'
      this.title = '优势：技术力量，产品质量；劣势：资金短缺，管理混乱'
      this.chance = '外部机会：新市场；威胁：经济衰退'
      this.outline = '200'
    },
    changeChance (e) {
      this.outline = e.detail.value
    },
    changeOutline (e) {
      this.outline = e.detail.value
    },
    changeMessage (e) {
      this.message = e.detail.value
    },
    changeTitle (e) {
      this.title = e.detail.value
    },
    changeValue (e) {
      this.writing = e.detail.value
    },
    async create () {
      if (!this.message) {
        uni.showToast({
          title: '邮件主题/邮件标题',
          icon: 'none',
          duration: 2000
        });
        return
      }
      if (!this.writing) {
        uni.showToast({
          title: '收件人所属角色',
          icon: 'none',
          duration: 2000
        });
        return
      }
      this.highOriginal();
    },
    clickTab (item, index) {
      if (index == 0) {
        this.show = false
      } else {
        let text = this.creativeResult
        // #ifdef H5
        let textarea = document.createElement("textarea")
        textarea.value = text
        textarea.readOnly = "readOnly"
        document.body.appendChild(textarea)
        textarea.select() // 选中文本内容
        textarea.setSelectionRange(0, text.length)
        uni.showToast({//提示
          title: '复制成功',
          icon: 'success'
        })
        document.execCommand("copy")
        textarea.remove()
        // #endif
        // #ifndef H5
        uni.setClipboardData({
          data: text,//要被复制的内容
          success: () => {//复制成功的回调函数
            uni.showToast({//提示
              title: `复制成功`,
              icon: 'success'
            })
          }
        }, true);
        // #endif

      }
    },
  },
}
</script>
<style lang="less">
.page {
  width: 100%;
  height: calc(100vh);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background:#E7F4FD;
}
.scroll-Y {
  width: 100%;
  height: 100%;
}
.page-view {
  width: 100%;
  height: 100%;
}
.title {
  width: 120%;
  height: 80rpx;
  margin: 0 0 0 -20px;
  box-sizing: border-box;
  padding: 0rpx 40rpx;
  display: flex;
  align-items: center;
  //   background-color: #F7F7F7;
  background-color: rgba(211, 238, 255, 0.5);
  font-size: 24rpx;
  color: #666666;
}
.context {
  width: 90%;
  margin: 0rpx auto;
  .context-tone {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .context-tone-item {
      width: 18%;
      padding: 12rpx 14rpx;
      // background-color: #F7F7F7;
      border: 1px solid #3f96f7;
      border-radius: 24rpx;
      font-size: 22rpx;
      //   margin-left: 15rpx;
      //   margin-right: 30rpx;
      //   margin-bottom: 30rpx;
      margin: 5px 0 0 8.3px;
      color: #333333;
      text-align: center;
    }
    .context-tone-item-select {
      //   background-color: #4BB591;
      background-color: #3474ff;
      color: #fff;
    }
  }
  .context-tip {
    width: 100%;
    height: 90rpx;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .context-tip-left {
      font-size: 30rpx;
      color: #333333;
      display: flex;
      align-items: center;
      /deep/.context-tip-left-tip span {
        color: red;
        margin-left: 6rpx;
        vertical-align: sub;
      }
    }
    .context-tip-right {
      color: #999999;
      font-size: 24rpx;
    }
  }
  .context-title {
    width: 100%;
    height: 90rpx;
    font-size: 30rpx;
    color: #333333;
    margin-top: 10px;
    display: flex;
    align-items: center;
    /deep/.context-title-tip span {
      color: red;
      margin-left: 6rpx;
      vertical-align: sub;
    }
  }
  .context-textarea {
    width: 100%;
    height: 240rpx;
    // background-color: #F7F7F7;
    border: 1px solid #3f96f7;
    border-radius: 24rpx;
    position: relative;
    .context-textarea-input {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 22rpx 30rpx 0 30rpx;
      color: #333333;
      font-size: 28rpx;
    }
    .context-textarea-max {
      position: absolute;
      right: 40rpx;
      bottom: 20rpx;
      color: #999999;
    }
  }
  .button {
    width: 90%;
    height: 90rpx;
    background-color: rgba(52, 116, 255, 0.3);
    border-radius: 60rpx;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 30rpx;
    margin: 40rpx auto 0rpx;
  }
}
.answer {
  width: 90%;
  margin: 0px auto;
  height: 90%;
  .answer-fontLength {
    width: 100%;
    height: 60rpx;
    color: #999999;
    font-size: 30rpx;
    // display: flex;
    // align-items: center;
    //padding-left: 520rpx;
    position: absolute;
    left: 76%;
  }
  .answer-value {
    width: 100%;
    height: 100rpx;
    color: #333333;
    font-size: 44rpx;
    line-height: 100rpx;
    // display: flex;
    // align-items: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .answer-textarea {
    width: 100%;
    height: 60%;
    // background-color: #F7F7F7;
    border: 1px solid #3f96f7;
    border-radius: 24rpx;
    .answer-textarea-input {
      width: 100%;
      height: 92%;
      box-sizing: border-box;
      padding: 30rpx 30rpx 20rpx;
      color: #333333;
      font-size: 28rpx;
    }
  }
}
.tabbar {
  width: 100%;
  //   height: 10%;
  //   background-color: #fff;
  display: flex;
  box-sizing: border-box;
  justify-content: center;
  //   border-top: 1rpx solid #e5dbdb;
  .tabbar-item {
    width: 33.33%;
    height: 68.84rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    // flex-direction: column;
    font-family: PingFang SC;
    padding: 0 40rpx;
    font-weight: 500;
    color: #ffffff;
    line-height: 36rpx;
    font-size: 24rpx;
    border: solid 2rpx;
    margin: 0 12rpx;
    background: #3474ff;
    border-radius: 34rpx;
  }
}

/deep/::-webkit-scrollbar {
  display: none;
  width: 0 !important;
  height: 0 !important;
  -webkit-appearance: none;
  background: transparent;
  color: transparent;
}

.schedule-page {
  width: 100%;
  height: 100vh;
  position: fixed;
  background-color: rgba(128, 126, 126, 0.8);
  top: 0px;
  left: 0px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
}
.schedule-box {
  width: 62%;
  background-color: #fff;
  border-radius: 15rpx;
}
.schedule-text {
  text-align: center;
  line-height: 120rpx;
}
.schedule {
  width: 100%;
  height: 20rpx;
  margin: 20rpx 0rpx;
}
.schedule-number {
  width: 100%;
  height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #2979ff;
}
.lineBox {
  width: 90%;
  display: flex;
  justify-content: space-around;
  margin: 0px auto;
  height: 12rpx;
  border-radius: 24rpx;
  overflow: hidden;
}
.lineAnimation {
  height: 100%;
  background-color: #bbb9b9;
}
.lineAnimation-children {
  height: 100%;
  transition: all 0.5s;
  background-color: #2979ff;
}
.baifenbizdy {
  color: skyblue;
  font-size: 22px;
  align-items: center;
  justify-content: center;
  display: flex;
  margin-top: 7%;
}
.isshow {
  background-color: #fff;
  border-radius: 10px;
  width: 90%;
  height: 190px;
  left: 5%;
  position: relative;
  top: -70%;
  font-size: 50px;
  z-index: 10086;
  color: #1890ff;
  padding: 40px 0 0 0;
}
.box {
  width: 880px;
  background: #ffffff;
  position: relative;
  // height: 640px;
}
.textzdy {
  display: flex;
  font-size: 22px;
  margin: auto;
  color: grey;
  align-items: center;
  justify-content: center;
  padding-top: 2%;
}
.container {
  width: 90%;
  height: 7px;
  background-color: #fafafc;
  border-radius: 15px;
  margin-left: 5%;
  margin-top: 8%;
}
/* 内部加载部分样式 */
.contentzdy {
  width: 100%;
  height: 7px;
  border-radius: 15px;
  background-color: #1890ff;
  text-align: center;
  line-height: 10px;
}
.jindu {
  margin-top: 1px;
}
</style>